package com.zw.sys.WebSocket;

import com.zw.netty.Server.NettyServer;
import com.zw.netty.Server.util.RequestMessage;
import com.zw.netty.Server.util.ResponseMessage;
import com.zw.common.ChatConstants;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Controller;

import javax.annotation.Resource;

/**
 * 创建人:zhuwei
 * 邮箱:121203654@qq.com
 * 创建时间:2018-04-26 17:36
 */
@Controller
public class WsController {

    @Resource
    private SimpMessagingTemplate template;

    @MessageMapping("/welcome")
    @SendTo("/topic/getResponse")
    public ResponseMessage say(RequestMessage message) {
        return new ResponseMessage("welcome," + message.getName() + " !");
    }

    @SendTo("/topic/userList")
    public Object callback() throws Exception {
        // 发现消息
        template.convertAndSend("/topic/userList", ChatConstants.onlines);
        return "userList";
    }
    @MessageMapping("/send")
    @SendTo("/topic/sendMessage")
    public Object send(RequestMessage message){
        System.out.println("发送消息");
        if(message.getToId().equals("0")){
            switch (message.getName()){
                case "1":NettyServer.channelGroup.writeAndFlush("@G#@,V01,25,@R#@");
                case "2":NettyServer.channelGroup.writeAndFlush("@G#@,V01,114,@R#@");
                case "3":NettyServer.channelGroup.writeAndFlush("@G#@,V01,115,@R#@");
            }

        }else{
            NettyServer.channelGroup.stream().forEach(channel -> {
                if(channel.id().asShortText().equals(message.getToId())&&channel.isWritable()){
                    switch (message.getName()){
                        case "1":channel.writeAndFlush("@G#@,V01,25,@R#@");
                        case "2":channel.writeAndFlush("@G#@,V01,114,@R#@");
                        case "3":channel.writeAndFlush("@G#@,V01,115,@R#@");
                    }
                }else{
                    System.out.println("发送失败"+channel.id().asShortText());
                }
            });
        }

        return "send";
    }

}
